package com.guoguo.api;

import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.map.HashedMap;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.guoguo.base.BaseController;
import com.guoguo.base.StaticResource;
import com.guoguo.entity.UserExt;
import com.guoguo.entity.Users;
import com.guoguo.enums.SMSEnum;
import com.guoguo.enums.UsersEnum;
import com.guoguo.service.IUserExtService;
import com.guoguo.service.IUsersService;
import com.guoguo.utils.HttpClientUtils;
import com.guoguo.utils.PropertyUtils;
import com.guoguo.utils.RedisUtils;
import com.guoguo.utils.SMSHxUtils;
import com.guoguo.utils.TokenUtils;
import com.guoguo.utils.UUIDUtils;

/**
 * Created by Administrator on 2017/8/15 0015.
 */
@RestController
@RequestMapping("/api")
public class AppLoginController extends BaseController {
    private Logger log = LoggerFactory.getLogger(AppLoginController.class);
    @Resource
    private IUsersService usersService;

    @Resource
    private IUserExtService iUserExtService;
    private String password;

    /**
     * 用户登录
     *
     * @param nickName  用户昵称
     * @param userName  用户名
     * @param userpwd   用户密码
     * @param loginType 登录类型 (0:帐号登录，1：第三方登录)
     * @param icon      用户头像
     * @param phoneType 手机类型
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public JSONObject findUser(HttpServletRequest request, @RequestParam String userName, @RequestParam String nickName,
                               @RequestParam String userpwd, @RequestParam int loginType, @RequestParam String icon, @RequestParam int phoneType) {

        boolean flag = false;
        Users users = null;
        if (loginType == 0) {
            //普通登录时，用户名和密码不能为空
            if (userName == null || "".equals(userName)) {
                return returnResult(UsersEnum.LOGIN_USER_ERROR.getId(), null, UsersEnum.LOGIN_USER_ERROR.getValue());
            }
            if (userpwd == null || "".equals(userpwd)) {
                return returnResult(UsersEnum.LOGIN_PWD_ERROR.getId(), null, UsersEnum.LOGIN_PWD_ERROR.getValue());
            }
            users = usersService.findUser(userName, userpwd);
        } else if (loginType == 1) {
            //第三方登录时，用户名不能为空
            if (userName == null || "".equals(userName)) {
                return returnResult(UsersEnum.LOGIN_USER_ERROR.getId(), null, UsersEnum.LOGIN_USER_ERROR.getValue());
            }
            try {
                nickName = new String(nickName.getBytes("iso-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            users = usersService.findUsers(userName, nickName, icon, Integer.valueOf(request.getHeader("appId")), phoneType);
        }
        Map<String, String> data = new HashMap<String, String>();
        if (users != null) {
            RedisUtils redisUtils = RedisUtils.getInstance();

            //当token验证通过，返回原token。没有token时，会创建一个新的token。
            if (redisUtils.exists(StaticResource.SYS_TOKEN_KEY + request.getHeader("token"))) {
                data.put("token", String.valueOf(request.getHeader("token")));
            } else {
                //生成token
                data.put("token", TokenUtils.getToken());
                redisUtils.set(StaticResource.SYS_TOKEN_KEY + data.get("token"), userName);
                //token有效期一天
                redisUtils.expire(StaticResource.SYS_TOKEN_KEY + data.get("token"), 3600 * 24);
            }
            data.put("userId", users.getUserId());
            return returnResult(UsersEnum.LOGIN_SUCCESS.getId(), data, UsersEnum.LOGIN_SUCCESS.getValue());
        } else {
            return returnResult(UsersEnum.LOGIN_ERROR.getId(), null, UsersEnum.LOGIN_ERROR.getValue());
        }

    }

    /**
     * 游客登录
     *
     * @param request
     * @param Mac
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/guestLogin", method = RequestMethod.POST)
    public JSONObject guestLogin(HttpServletRequest request, @RequestParam String Mac) {

        if (Mac == null || "".equals(Mac)) {
            return returnResult(UsersEnum.MAC_NULL.getId(), null, UsersEnum.MAC_NULL.getValue());
        }
        Map<String, String> data = new HashMap<String, String>();
        RedisUtils redisUtils = RedisUtils.getInstance();
        if (redisUtils.exists(StaticResource.SYS_TOKEN_KEY + request.getHeader("token"))) {
            data.put("token", String.valueOf(request.getHeader("token")));
        } else {
            data.put("token", TokenUtils.getToken());
            redisUtils.set(StaticResource.SYS_TOKEN_KEY + data.get("token"), Mac);
        }
        return returnResult(UsersEnum.LOGIN_SUCCESS.getId(), data, UsersEnum.LOGIN_SUCCESS.getValue());

    }

    /**
     * 用户注册
     *
     * @param phone
     * @param valiCode
     * @param userpwd
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public JSONObject userRegister(@RequestParam String userName, @RequestParam String phone, @RequestParam String
            valiCode, @RequestParam int phonetype, @RequestParam String userpwd, HttpServletRequest request) {
        Map<String, Object> data = new HashMap();
        RedisUtils redisUtils = RedisUtils.getInstance();
        String isScrUser = null;
        Integer addCount = null;
        //验证码是否过期
        if (redisUtils.exists(StaticResource.SYS_VALICODE_REG + phone)) {
            String valicode = redisUtils.getString(StaticResource.SYS_VALICODE_REG + phone);
            //验证码错误
            if (!valicode.equals(valiCode)) {
                //注册失败
                return returnResult(UsersEnum.REGISTER_VALICODE_ERROR.getId(), data, UsersEnum.REGISTER_VALICODE_ERROR.getValue());
            } else {
                Users user = new Users();
                UserExt userExt = new UserExt();
                user.setUserId(UUIDUtils.getUUID());
                user.setUsername(userName);
                user.setUserpwd(userpwd);
                user.setPhone(phone);
                user.setNickname(userName);
                user.setAppId(Integer.valueOf(request.getHeader("appId")));
                user.setPhoneType(phonetype);
                int users = usersService.insertUsers(user);
                userExt.setUserId(user.getUserId());
                userExt.setEmail(null);
                userExt.setPhone(user.getPhone());
                Date now = new Date();
                userExt.setRegistered(now);
                userExt.setCreateTime(now);
                userExt.setSex(false);
                userExt.setIcon(null);
                userExt.setBuyCount(0);

                userExt.setBuySurplus(0);
                userExt.setIsMember(false);
                userExt.setMemType(null);
                userExt.setMoney(null);

                //查询注册的用户是否被邀请过
                isScrUser = usersService.selectUserIsHaveSrcUser(phone);
                if (StringUtils.isNotBlank(isScrUser) && !isScrUser.equals("null")) {
                    userExt.setPoint(1000L);
                    addCount = iUserExtService.addSrcUserPoint(isScrUser);
                } else {
                    userExt.setPoint(null);
                }
                iUserExtService.insertUserExt(userExt);

                Map<String, String> params = new HashedMap();
                params.put("userName", userName);
                params.put("nickName", user.getNickname());
                params.put("loginType", "0");
                params.put("icon", "");
                params.put("appId", String.valueOf(user.getAppId()));
                params.put("phoneType", String.valueOf(phonetype));
                params.put("userpwd", user.getUserpwd());

                //注册成功
                //调用login
                String loginApiUrl = PropertyUtils.getProperty("api.properties", "api.domainName") + "/api/login";
                log.info("===============>>>>>>    loginApiUrl : " + loginApiUrl);
                String result = HttpClientUtils.doPost(loginApiUrl, params, "utf-8");
                JSONObject resultJson = JSON.parseObject(result);
                return resultJson;
            }
        } else {
            //验证码过期
            return returnResult(UsersEnum.REGISTER_VALICODE_EXPIRED.getId(), data, UsersEnum.REGISTER_VALICODE_EXPIRED.getValue());
        }

    }

    /**
     * 发送验证码短信
     * 验证码在缓存里存在5分钟
     *
     * @param phoneNo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sendViliCode", method = RequestMethod.POST)
    public JSONObject sendViliCode(@RequestParam String phoneNo, @RequestParam int smsType) {
        String valiCode = String.valueOf(Double.valueOf((Math.random() * 9 + 1) * 100000).intValue());
        String message = new String();
        String redisKey = new String();

        if (smsType == 0) {
            message = MessageFormat.format(SMSEnum.SMS_TEMPLATE_VALICODE.getValue(), valiCode);
            redisKey = StaticResource.SYS_VALICODE_REG + phoneNo;
        } else {
            message = MessageFormat.format(SMSEnum.SMS_TEMPLATE_PASSWORD.getValue(), valiCode);
            redisKey = StaticResource.SYS_VALICODE_PWD + phoneNo;
        }
        RedisUtils redisUtils = RedisUtils.getInstance();

        redisUtils.set(redisKey, valiCode);
        //设置验证码过期时间
        redisUtils.expire(redisKey, 300);
        SMSHxUtils.sendMassage(phoneNo, message);
        return returnResult(UsersEnum.SMS_SEND_SUCCESS.getId(), "", UsersEnum.SMS_SEND_SUCCESS.getValue());
    }

    /**
     * 找回密码
     *
     * @param userName 用户名
     * @param userpwd  密码
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateUserpwd", method = RequestMethod.POST)
    public JSONObject updateUserpwd(@RequestParam String userName, @RequestParam String
            valiCode, @RequestParam String userpwd) {

        Map<String, Object> data = new HashMap<String, Object>();
        RedisUtils redisUtils = RedisUtils.getInstance();

        if (userName == null) {
            return returnResult(UsersEnum.LOGIN_USER_ERROR.getId(), data, UsersEnum.LOGIN_USER_ERROR.getValue());
        } else {
            //验证码是否过期
            if (redisUtils.exists(StaticResource.SYS_VALICODE_PWD + userName)) {
                String valicode = redisUtils.getString(StaticResource.SYS_VALICODE_PWD + userName);
                //验证码错误
                if (!valicode.equals(valiCode)) {
                    return returnResult(UsersEnum.REGISTER_VALICODE_ERROR.getId(), data, UsersEnum.REGISTER_VALICODE_ERROR.getValue());
                }

                return returnResult(UsersEnum.UPDATEUSERPWD_SUCCESS.getId(), data, UsersEnum.UPDATEUSERPWD_SUCCESS.getValue());
            } else {
                return returnResult(UsersEnum.REGISTER_VALICODE_EXPIRED.getId(), data, UsersEnum.REGISTER_VALICODE_EXPIRED.getValue());
            }
        }
    }
}
